package com.lzy.business.controller.sys;

import com.github.pagehelper.PageInfo;
import com.lzy.base.apis.*;
import com.lzy.base.constants.Constants;
import com.lzy.base.dtos.DeptDto;
import com.lzy.base.dtos.SysRoleDto;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.base.utils.UserUtil;
import com.lzy.business.controller.BaseController;
import com.lzy.business.facade.SysUserAdminServiceFacade;
import com.lzy.business.request.ProductUserRequest;
import com.lzy.common.constants.BusinessType;
import com.lzy.framework.common.dtos.LicenseDto;
import com.lzy.framework.component.PageBean;
import com.lzy.framework.constants.CommonConstants;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.QiniuUtils;
import com.lzy.product.apis.ProductUserServiceApi;
import com.lzy.product.dtos.ProductUserDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("admin/manager")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserAdminServiceApi sysUserAdminServiceApi;
    @Autowired
    private SysRoleServiceApi sysRoleServiceApi;
    @Autowired
    private SysUserRoleServiceApi sysUserRoleServiceApi;
    @Autowired
    private DeptServiceApi deptServiceApi;
    @Autowired
    private SysUserAdminServiceFacade sysUserAdminServiceFacade;
    @Autowired
    private ProductUserServiceApi productUserServiceApi;

    /**
     * 默认页面
     **/
    @RequestMapping(method = RequestMethod.GET)
    public String list() {
        return "admin/userList";
    }

    /**
     * 获取用户数据列表
     **/
//    @RequiresPermissions("sys:manager:view")
    @RequestMapping(value = "json", method = RequestMethod.GET)
    @ResponseBody
    public PageBean getData(SysUserAdminDto request) {
        Ensure.that(request).isNotNull("00000004");
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        String roleList = new String();
        PageInfo<SysUserAdminDto> pageInfo;
        if (request.getListType() != null && request.getListType().equals("auditors")) {
            roleList = roleList + BusinessType.SysRoleType.SYS.getCode();
            pageInfo = sysUserAdminServiceApi.selectByRoleList(pager, roleList);
        } else {
            pageInfo = sysUserAdminServiceApi.queryUserList(pager, request, null);
            Ensure.that(pageInfo).isNotNull("01001119");
        }
        if (pageInfo != null && pageInfo.getList() != null) {
            return new PageBean<>(pageInfo.getTotal(), pageInfo.getList());
        } else {
            return new PageBean();
        }
    }

    /**
     * 获取用户数据列表
     **/
//    @RequiresPermissions("sys:manager:view")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public PageBean getUserList(ProductUserRequest request) {
        Ensure.that(request).isNotNull("00000004");
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        PageInfo<ProductUserDto> pageInfo = productUserServiceApi.queryUserList(pager, DozerUtils.map(request, ProductUserDto.class));
        Ensure.that(pageInfo).isNotNull("01001119");
        if (pageInfo != null && pageInfo.getList() != null) {
            return new PageBean<>(pageInfo.getTotal(), pageInfo.getList());
        } else {
            return new PageBean();
        }
    }

    /**
     * 添加用户跳转
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        //部门信息
        List<DeptDto> deptList = deptServiceApi.getDeptDtos(null);
        model.addAttribute("deptList", deptList);
        model.addAttribute("adminUser", new SysUserAdminDto());
        model.addAttribute("action", "create");
        return "admin/userForm";
    }

    /**
     * 添加用户
     *
     * @param productUserDto
     * @param bindingResult
     * @return
     */
//    @RequiresPermissions("sys:manager:add")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public Result create(@Valid ProductUserDto productUserDto, BindingResult bindingResult) {
        Ensure.that(sysUserAdminServiceApi.selectExistPhone(productUserDto.getPhone())).isFalse("05000001");
        Result result = new Result();
        if (!productUserDto.getLoginName().matches(CommonConstants.REGULAR.LOGIN_NAME)) {
            Ensure.that("").isNotBlank("05000002");
        }
        Ensure.that(bindingResult.hasErrors()).isFalse("05000002");
        productUserDto.setDataType(UserUtil.getCurrentUser().getDataType());
        sysUserAdminServiceFacade.addUser(productUserDto);
        return result;
    }


    /**
     * 跳转至修改用户页面
     *
     * @param id
     * @param model
     * @return
     */
//    @RequiresPermissions("sys:manager:update")
    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateUser(@PathVariable("id") Long id, Model model) {
        ProductUserDto userDto = productUserServiceApi.findById(id);
        //部门信息
        List<DeptDto> deptList = deptServiceApi.getDeptDtos(null);
        model.addAttribute("deptList", deptList);
        model.addAttribute("adminUser", userDto);
        model.addAttribute("action", "update");
        return "admin/userForm";
    }

    /**
     * 查看用户信息
     */
//    @RequiresPermissions("sys:manager:userView")
    @RequestMapping(value = "view/{id}", method = RequestMethod.GET)
    public String viewUser(@PathVariable("id") Long id, Model model) {
        ProductUserDto userDto = productUserServiceApi.findById(id);
        //部门信息
        if (userDto != null) {
            DeptDto dept = deptServiceApi.findDeptDtoById(userDto.getDeptId());
            if (dept != null) {
                userDto.setDeptName(dept.getDeptName());
            }
        }
        model.addAttribute("adminUser", userDto);
        model.addAttribute("userId", id);
        return "admin/user_view";
    }

    /**
     * 修改用户信息
     *
     * @param userDto
     * @return
     */
//    @RequiresPermissions("sys:manager:update")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateRole(@Valid @ModelAttribute("adminUser") ProductUserDto userDto) {
        Result result = new Result();
        Boolean flag = productUserServiceApi.update(userDto);
        Ensure.that(flag).isTrue("");
        return result;
    }

    /**
     * 修改用户头像（sysUserAdmin and shop）
     *
     * @param file
     * @return
     */
//    @RequiresPermissions("sys:manager:update")
    @RequestMapping(value = "/avatar/upload", method = RequestMethod.POST)
    @ResponseBody
    public String updateUserAvatar(@RequestParam(value = "image", required = false) MultipartFile file) {
        String avatar = QiniuUtils.upload(file, QiniuUtils.QINIU_BUCKET_DOMAIN_ENUM.GOODS);
        SysUserAdminDto sysUserAdmin = new SysUserAdminDto();
        sysUserAdmin.setAvatar(avatar);
        sysUserAdmin.setId(UserUtil.getCurrentUser().getId());
        sysUserAdminServiceApi.update(sysUserAdmin);
        SecurityUtils.getSubject().getSession().getAttribute(Constants.SYS_USER);
        SysUserAdminDto sessionUser = sysUserAdminServiceApi.selectByPrimaryKey(UserUtil.getCurrentUser().getId());
        // 刷新用户session
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(Constants.SYS_USER, sessionUser);
        return avatar;
    }


    /**
     * 修改平台用户状态
     *
     * @param id
     * @param state
     * @return
     */
//    @RequiresPermissions("sys:manager:comp:updateStatus")
    @RequestMapping(value = "updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public Result updateStatus(@RequestParam("id") Long id, @RequestParam("state") int state) {
        Result result = new Result();
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi.selectByPrimaryKey(id);
        Ensure.that(sysUserAdmin.getSex()).isNotEqualTo(Constants.SYS_USER_ADMIN, "01001134");
        sysUserAdmin.setState(state);
        sysUserAdminServiceApi.updateByPrimaryKeySelective(sysUserAdmin);
        return result;
    }

    /**
     * 修改企业用户状态
     *
     * @param id
     * @param state
     * @return
     */
//    @RequiresPermissions("sys:manager:comp:updateStatus")
    @RequestMapping(value = "updateCompStatus", method = RequestMethod.POST)
    @ResponseBody
    public Result oplogUpdateCompStatus(@RequestParam("id") Long id,
                                        @RequestParam("state") int state) {
        Result result = new Result();
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi
                .selectByPrimaryKey(id);
        List<SysUserAdminDto> sysUserAdmins = sysUserAdminServiceApi
                .selectByCompCoreId(sysUserAdmin.getCompanyId());
        for (int i = 0; i < sysUserAdmins.size(); i++) {
            sysUserAdmins.get(i).setState(state);
            sysUserAdminServiceApi.updateByPrimaryKeySelective(sysUserAdmins
                    .get(i));
        }
        return result;
    }

    /**
     * 删除用户
     *
     * @return
     */
//    @RequiresPermissions("sys:manager:delete")
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteRole(SysUserAdminDto sysUserAdmin) {
//        sysUserAdminServiceApi.delete(sysUserAdmin.getId());//数据删除
        sysUserAdminServiceApi.deleteUser(sysUserAdmin.getId());//逻辑删除
        return new Result();
    }

    /**
     * 分配角色跳转
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "roleUpdate", method = RequestMethod.GET)
    public String roleUpdate(@RequestParam("id") String id, Model model) {
        model.addAttribute("userId", id);
        return "admin/roleSelect";
    }

    /**
     * 获取角色列表
     *
     * @return
     */
//    @RequiresPermissions("sys:manager:roleView")
    @RequestMapping(value = "role/json", method = RequestMethod.GET)
    @ResponseBody
    public List<SysRoleDto> getRoles(@RequestParam("userId") Long userId) {
        SysRoleDto sysRoleDto = new SysRoleDto();
        sysRoleDto.setCompanyId(UserUtil.getCurrentUser().getCompanyId());
        //按照级别递进判断
        if (isShop())
            sysRoleDto.setType(-1);
        if (isBase())
            sysRoleDto.setType(BusinessType.SysRoleType.OPERATION.getCode());
        if (isAdmin())
            sysRoleDto.setType(null);
        List<SysRoleDto> result = sysRoleServiceApi.selectAllByCompany(sysRoleDto);
        //若当前是总运营管理角色，则去除当前角色，拿到细分的运营角色
        if (isBase()) {
            List<SysRoleDto> tmpResult = new ArrayList<>();
            for (SysRoleDto dto : result) {
                if (!dto.getId().equals(BusinessType.RoleType.BASE_ROLE.getCode()))
                    tmpResult.add(dto);
            }
            result = tmpResult;
        }
        List<Long> roleIds = sysUserRoleServiceApi.getRoleIdList(userId);
        if (UserUtil.getCurrentUser().getCompanyId() == null) {
            result.remove(result.get(0));
        }
        if (roleIds == null || roleIds.size() == 0)
            return result;
        for (int i = 0; i < result.size(); i++) {
            long roleId = result.get(i).getId();
            if (roleIds.contains(roleId)) {
                result.get(i).setChecked(Boolean.TRUE);
            }
        }
        return result;
    }

    /**
     * 更改角色分配
     **/
//    @RequiresPermissions("sys:manager:roleUpdate")
    @RequestMapping(value = "{userId}/updateUserRole")
    @ResponseBody
    public Result updateUserRole(@PathVariable("userId") Long userId,
                                 @RequestBody List<Long> newRoleIds) {
        Result result = new Result();
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi.selectByPrimaryKey(userId);
        Ensure.that(sysUserAdmin.getSex()).isNotEqualTo(Constants.SYS_USER_ADMIN, "01001122");
        List<Long> oldRoleIds = sysUserRoleServiceApi.getRoleIdList(userId);
        sysUserRoleServiceApi.updateUserRole(userId, oldRoleIds, newRoleIds);
        return result;
    }

    /**
     * 修改密码跳转
     **/
    @RequestMapping(value = "changePwd", method = RequestMethod.GET)
    public String updatePwd(Model model) {
        model.addAttribute("userId", UserUtil.getCurrentUser().getId());
        model.addAttribute("action", "update");
        return "admin/changePwd";
    }

    /**
     * 更改密码
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "changePwd", method = RequestMethod.POST)
    @ResponseBody
    public Result pwdUpdatePwd(HttpServletRequest request, HttpSession session) {
        //前端进行第一次加密
        String oldPassword = request.getParameter("oldPassword").replace(
                " ", "");
        String newPassword = request.getParameter("newPassword").replace(
                " ", "");
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi.selectByPrimaryKey(UserUtil.getCurrentUser().getId());
        //判断原密码是否正确
        Ensure.that(sysUserAdminServiceApi.checkPassword(sysUserAdmin, oldPassword)).isTrue("01001132");
        sysUserAdminServiceFacade.editPwd(sysUserAdmin, newPassword);
        session.setAttribute(Constants.SYS_USER, sysUserAdmin);
        return new Result();
    }

    /**
     * 重置密码
     *
     * @param id
     * @param session
     * @return
     */
//    @RequiresPermissions("sys:manager:resetPwd")
    @RequestMapping(value = "resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public Result pwdResetPwd(@RequestParam("id") Long id, HttpSession session) {
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi.selectByPrimaryKey(id);
        Ensure.that(sysUserAdmin).isNotNull("01001131");
        //重置密码，第一次加密
//        sysUserAdminServiceFacade.editPwd(sysUserAdmin, MD5Utils.MD5(PasswordUtil.defaultPass));
        session.setAttribute(Constants.SYS_USER, sysUserAdmin);
        return new Result();
    }

    @RequestMapping(value = "checkLoginName", method = RequestMethod.GET)
    @ResponseBody
    public boolean checkLoginName(@RequestParam("loginName") String loginName) {
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi
                .selectByLoginName(loginName);
        if (sysUserAdmin != null) {
            return false;
        } else {
            return true;
        }
    }

    @RequestMapping(value = "checkCompLoginName", method = RequestMethod.GET)
    @ResponseBody
    public boolean checkCompLoginName(
            @RequestParam("registerName") String loginName) {
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi
                .selectByLoginName(loginName);
        if (sysUserAdmin != null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 修改密码跳转
     **/
    @RequestMapping(value = "changeLoginName", method = RequestMethod.GET)
    public String changeLoginName(Model model) {
        model.addAttribute("action", "update");
        return "admin/changeLoginName";
    }

    /**
     * 更改登录名跳转
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "changeLoginName", method = RequestMethod.POST)
    @ResponseBody
    public Result logChangeLoginName(HttpServletRequest request, HttpSession session) {
        List<Long> listId = sysUserRoleServiceApi.getRoleIdList(UserUtil.getCurrentUser().getId());
        boolean flag = listId.contains(BusinessType.RoleType.SUPER_ADMIN.getCode());
        if (flag == true) {
            Ensure.that(UserUtil.getCurrentUser().getId()).isEqual(BusinessType.RoleType.SUPER_ADMIN.getCode(), "01001128");
        }
        String newLoginName = request.getParameter("loginName").trim();
        Ensure.that(request.getParameter("loginName")).isNotNull("01001129");
        Ensure.that(request.getParameter("loginName")).isNotBlank("01001129");
        SysUserAdminDto sysFindUser = sysUserAdminServiceApi.selectByLoginName(newLoginName);
        if (sysFindUser != null && sysFindUser.getId() != UserUtil.getCurrentUser().getId()) {
            Ensure.that("11020028").isNotBlank("当前登录名已存在，请重新输入");
        }
        SysUserAdminDto sysUserAdmin = sysUserAdminServiceApi.selectByPrimaryKey(UserUtil.getCurrentUser().getId());
        sysUserAdmin.setLoginName(newLoginName);
        sysUserAdminServiceApi.updateByPrimaryKeySelective(sysUserAdmin);
        session.setAttribute(Constants.SYS_USER, sysUserAdmin);
        return new Result();
    }

    /**
     * 添加用户（用户的身份绑定、角色绑定）
     *
     * @param sysUserAdmin //     * @param sysUserIdentity
     * @return
     */
//    @RequiresPermissions("sys:manager:add")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Result userIdentityAdd(SysUserAdminDto sysUserAdmin) {
        // SysUserAdminRequest sysUserIdentity) {
        LicenseDto lic = new LicenseDto();
        lic.setCode("");
        lic.setUrl("");
//        sysUserAdminServiceFacade.userIdentityAdd(sysUserAdmin, DozerUtils.map(sysUserIdentity, SysUserIdentityDto.class), null, getCurrentUserStr(), lic);

        return new Result();
    }

    /**
     * （设置）修改密码
     */
//    @RequiresPermissions("sys:password:update")
    @RequestMapping(value = "/settings/password", method = RequestMethod.GET)
    public String toSettingsPassword(Model model) {
        return "company/settings_password";
    }

    /**
     * @Author:liyx
     * @Description:找回密码跳转
     * @Date:2017/8/7 10:06
     */
    @RequestMapping(value = "retrievePassword", method = RequestMethod.GET)
    public String retrievePassword(Model model) {
        model.addAttribute("action", "update");
        return "admin/changeLoginName";
    }

    /**
     * @Author:liyx
     * @Description:找回密码
     * @Date:2017/8/7 10:07
     */
    @RequestMapping(value = "retrievePassword", method = RequestMethod.POST)
    @ResponseBody
    public Result retrievePassword(@RequestParam("phone") String phone, @RequestParam("newPassword") String newPassword) {
        SysUserAdminDto dto = sysUserAdminServiceApi.selectByPhone(phone);
        Ensure.that(dto).isNotNull("01001130");
//        sysUserAdminServiceFacade.editPwd(dto,newPassword);
        return new Result();
    }

    /**
     * 修改推荐人列表
     **/
    @RequestMapping(value = "userPermission", method = RequestMethod.GET)
    public String userPermission(Model model) {
        model.addAttribute("userId", UserUtil.getCurrentUser().getId());
        model.addAttribute("action", "update");
        return "admin/userPermission";
    }
}
